/**
 * @author  yuqiangfei
 * @desc    地区下拉插件js
 */
layui.define('config', function (exports) {
    var config = layui.config;
    (function ($) {
        var settings = {
            url: null,
            type: "GET",
            length: 3,
            okBtn: false, /**确认按钮*/
            liclick: true
        };

        //格式化字符串
        function format() {
            if (arguments.length == 1) return arguments[0];
            for (var s = arguments[0], i = 1; i < arguments.length; i++)
                s = s.replace(new RegExp("\\{" + (i - 1) + "\\}", "g"), arguments[i]);
            return s;
        }

        //添加选项
        function addSelect($input, parentId, currentId) {

            var responseData = null;
            $.ajax({
                url: settings.url,
                type: settings.type,
                data: {parentId: parentId},
                dataType: 'json',
                cache: true,
                async: false,
                success: function (data) {
                    responseData = data;
                }
            });

            if (responseData && responseData.length != 0) {

                var dataId = '';
                var dataName = '';
                var dataParent = '';
                var dataChoose = '请选择';

                //先清空a标签
                $input.siblings("dl").find('dd .tab-con a').remove();
                for (var i = 0; i < responseData.length; i++) {
                    var a = '<a href="javascript:;" title="' + responseData[i].name + '" data-id="' + responseData[i].id + '" data-name="' + responseData[i].name + '" data-parent="' + responseData[i].parent + '">' + responseData[i].name + '</a>';
                    $input.siblings("dl").find('dd .tab-con').append(a);
                    if (currentId == responseData[i].id) {
                        dataChoose = responseData[i].name;
                        dataId = responseData[i].id;
                        dataName = responseData[i].name;
                        dataParent = responseData[i].parent;
                    }
                }

                var li = format('<li class="on" data-id="{0}" data-name="{1}" data-parent="{2}">{3}</li>', dataId, dataName, dataParent, dataChoose);

                $input.siblings("dl").find('dd .tab li').attr('class', '');
                $input.siblings("dl").find('dd .tab').append(li);
            }

            if (currentId && $input.siblings("dl").find('dd .tab li').length > 0) {
                setValue($input);
            }


        }

        function setValue($input) {

            //设置隐藏框地区id
            var id = $input.siblings("dl").find('dd .tab li:last-child').attr('data-id');
            if (!id) {
                id = $input.siblings("dl").find("dd .tab li:nth-last-child(2)").attr('data-id');
            }
            $input.val(id);
            //设置显示文字
            var dtHtml = '';
            $input.siblings("dl").find('dd .tab li').each(function () {
                dtHtml += $(this).attr('data-name');
                var thisId = $(this).attr('data-id');
                if (id != thisId) {
                    dtHtml += '-';
                }
            });

            dtHtml = dtHtml.replace(/-$/gi, "");

            var dt = $input.siblings("dl").children('dt');
            //截取
            var width = dt.width();
            var fontSize = parseInt(dt.css('font-size'));
            var length = Math.ceil(width / fontSize) - 3;
            if (dtHtml.length > length) {
                dtHtml = dtHtml.substr(0, length - 1) + '...';
            }
            dt.html(dtHtml);

            //隐藏dt标签
            $input.siblings("dl").children('dd').hide();

            //触发areaId change事件
            $input.trigger('change');
        }


        $.fn.areaInit = function (options) {
            $.extend(settings, options);

            return this.each(function () {
                var $input = $(this);
                var areaId = $input.val();
                var treePath = $input.attr("treepath");
                var placeholder = $input.attr("placeholder") || '';
                var dock = $input.attr("dock");
                var cls = $input.attr("class") || '';
                var $select = '<dl class="m-select ' + cls + '">';
                $select += '<dt placeholder="' + placeholder + '"></dt>';
                if ("right" == dock) {
                    $select += '<dd class="region" style="right: 0px">';
                } else {
                    $select += '<dd class="region">';
                }
                $select += '<ul class="tab">';
                $select += '</ul>';
                $select += '<div class="tab-con">';
                $select += '</div>';

                $select += '<div class="tab-group">';
                $select += '<div class="tab-btn clear">清空</div>';
                if (settings.okBtn) {
                    $select += '<div class="tab-btn ok">确认</div>';
                }
                $select += '</div>';

                $select += '</dd>';
                $select += '</dl>';

                $($select).insertAfter($input).bind('click', function (e) {

                    $('.region').hide();

                    //显示dd标签
                    $input.siblings("dl").children('dd').show();

                    $(document).one('click', function () {
                        $input.siblings("dl").children('dd').hide();
                    });
                    e = e || event;
                    e.stopPropagation();
                });
                //防止选择地区时dd标签消失
                $input.siblings("dl").children('dd').click(function (e) {
                    e = e || event;
                    e.stopPropagation();
                });

                if (treePath) {//treePath不为空时
                    if (areaId && areaId != '') {
                        treePath += areaId;
                    }
                    var ids = treePath.split(',');
                    for (var i = 1; i < ids.length; i++) {
                        addSelect($input, ids[i - 1], ids[i]);
                    }
                } else {
                    addSelect($input, null, null);
                }
                //点击li标签
                if (settings.liclick) {
                    $input.siblings("dl").find('dd .tab').on('click', 'li', function () {
                        $input.siblings("dl").find('dd .tab li').attr('class', '');
                        $(this).attr('class', 'on');

                        var id = $(this).attr('data-id');
                        var parent = $(this).attr('data-parent');

                        if (!parent) {
                            return;
                        }

                        //删除当前li标签后面的li标签，然后删除当前li标签
                        $(this).nextAll().remove();
                        $(this).remove();

                        addSelect($input, parent, null);
                    });
                }

                $input.siblings("dl").find('.tab-group .clear').click(function () {
                    $input.val('');
                    $input.siblings("dl").children('dt').html('');

                    //隐藏dt标签
                    $input.siblings("dl").children('dd').hide();

                    //触发areaId change事件
                    $input.trigger('change');
                });
                $input.next().find('.tab-group .ok').click(function () {
                    setValue($input);
                });

                //点击a标签
                $input.next().find('dd .tab-con').on('click', 'a', function () {

                    var length = $input.siblings("dl").find('dd .tab li').length;

                    var id = $(this).attr('data-id');
                    var name = $(this).attr('data-name');
                    var parent = $(this).attr('data-parent');

                    var last_li = $input.siblings("dl").find('dd .tab li:last-child')
                    last_li.attr('data-id', id);
                    last_li.attr('data-name', name);
                    last_li.attr('data-parent', parent);
                    last_li.html(name);

                    if (length == settings.length) {
                        setValue($input);
                    } else {
                        addSelect($input, id, null);
                    }
                });
            })
        };

        $.fn.areaClear = function () {
            $(this).val('');
            $(this).next().children('dt').html('');

            //隐藏dt标签
            $(this).next().children('dd').hide();

            //触发areaId change事件
            $(this).trigger('change');
        }
    })(jQuery);


    var methods = {
        init: function (el, url) {
            $(el || "input[area-init]").each(function () {
                var $self = $(this);
                var paramsStr = $self.attr("area-init");
                var params = {};
                if (paramsStr) {
                    params = eval("(" + paramsStr + ")");
                }
                if (!url) {
                    params.url = "/cms/area/select";
                }
                $self.areaInit(params);
            })
        }
    };
    layui.link('public/module/area/area.css?v=' + config.version);
    exports('area', methods);
});